import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted } from 'vue'
import { suerinfoGetService } from '../api/admin/user'
export function useECharts(targetId, theme = 'back') {
  const chartInstance = ref(null)
  const userinfoview = ref([])
  const ageCount = [0, 0, 0]

  onMounted(async () => {
    const chart = echarts.init(document.getElementById(targetId), theme)
    const res = await suerinfoGetService() // 注意这里使用了 async/await

    userinfoview.value = res.data.data

    for (let i = 0; i < userinfoview.value.length; i++) {
      const age = parseInt(userinfoview.value[i].age)
      if (18 <= age && age <= 30) {
        ageCount[0]++
      } else if (31 <= age && age <= 60) {
        ageCount[1]++
      } else {
        ageCount[2]++
      }
    }
    initChart(chart, ageCount)
    chart.resize()
    chartInstance.value = chart
  })
  onUnmounted(() => {
    if (chartInstance.value) {
      chartInstance.value.dispose()
    }
  })

  return { chartInstance }
}
function initChart(chart, userinfo) {
  const ageRanges = ['18-30', '31-60', '61-70']
  const data = ageRanges.map((range, i) => ({
    value: userinfo[i],
    name: range
  }))
  let startAngle = 90 // 初始起始角度设置为90度

  chart.setOption({
    title: {
      text: '用户年龄图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    series: [
      {
        name: '年龄段分布',
        type: 'pie',
        radius: [10, 90],
        roseType: 'radius',
        startAngle: startAngle,
        data: data,
        animationType: 'scale',
        animationDuration: 1000,
        emphasis: {
          scale: true,
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // setInterval(() => {
  //   startAngle += 3 // 每秒增加1度
  //   chart.setOption({
  //     series: [
  //       {
  //         startAngle: startAngle
  //       }
  //     ]
  //   })
  // }, 200) // 每秒钟执行一次
}
